/**
 * 
 */
package com.ht.util;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.StrUtil;
import com.ht.constant.BusConstant;
import com.ht.constant.DicConstants;
import lombok.experimental.UtilityClass;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;


/**
 * 公共静态方法类
 * @author hejialun
 * @since 2021/4/22 15:30
 */
@UtilityClass
public class CommMethod {
	//1667543564000
	public static void main(String[] args) throws ParseException {
		String format="yyyy-MM-dd HH:mm:ss";
		String st="1667543564000";
	/*	Date date = new Date(1667543564000L);
		SimpleDateFormat fmt = new SimpleDateFormat(format);
		String dateStr = fmt.format(date);
		System.err.println(dateStr);*/
//		System.err.println(LocalDateTime.parse(date, DateTimeFormatter.ofPattern(format)));
		System.err.println(LocalDateTime.parse((CharSequence) new Date(Long.parseLong(st))));
	}

	private final String UNKNOWN = "unknown";


	public String getIP(HttpServletRequest request) {
		Assert.notNull(request, "HttpServletRequest is null");
		String ip = request.getHeader("X-Requested-For");
		if (StrUtil.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}
		if (StrUtil.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StrUtil.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StrUtil.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (StrUtil.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (StrUtil.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return StrUtil.isBlank(ip) ? null : ip.split(",")[0];
	}


	/**
	 * 创建对象初始化
	 * @param obj
	 */
	public static void beanCreate(Object obj){
		//设置创建时间
		setFieldValueByName(obj,"createDate",LocalDateTime.now());
		//设置部门id
		setFieldValueByName(obj,"deptId",UserUtil.getDeptId());
		//设置创建人
		setFieldValueByName(obj,"createUser",UserUtil.getUserId());
		//设置状态
		setFieldValueByName(obj,"state", DicConstants.State.ENABLE);
		//设置软删除
		setFieldValueByName(obj,"delFlag", BusConstant.DEL_FLAG_N);
	}
	/**
	 * 创建对象初始化-不设置部门id
	 * @param obj
	 */
	public static void beanCreateNoDept(Object obj){
		//设置创建时间
		setFieldValueByName(obj,"createDate",LocalDateTime.now());
		//设置创建人
		setFieldValueByName(obj,"createUser",UserUtil.getUserId());
		//设置状态
		setFieldValueByName(obj,"state", DicConstants.State.ENABLE);
		//设置软删除
		setFieldValueByName(obj,"delFlag", BusConstant.DEL_FLAG_N);
	}
	/**
	 * 修改对象初始化
	 * @param obj
	 */
	public static void beanUpdate(Object obj){
		//设置创建时间
		setFieldValueByName(obj,"updateDate",LocalDateTime.now());
		//设置创建人
		setFieldValueByName(obj,"updateUser",UserUtil.getUserId());
	}


	/**
	 * 通过反射写一个类，类中有个方法。
	 * 该方法可以设置某个类中的某个属性（构造方法，成员变量，成员方法）为特定的值
	 * @param obj
	 * @param fieldName
	 * @param value
	 */
	public static void setFieldValueByName(Object obj, String fieldName, Object value){
		try {
			// 获取obj类的字节文件对象
			Class c = obj.getClass();
			// 获取该类的成员变量
			Field f = c.getDeclaredField(fieldName);
			if(f!=null){
				// 取消语言访问检查
				f.setAccessible(true);
				// 给变量赋值
				f.set(obj, value);
			}
		} catch (Exception e) {

		}

	}

	/**
	 * 根据属性名获取属性值
	 * */
	private Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter, new Class[] {});
			Object value = method.invoke(o, new Object[] {});
			return value;
		} catch (Exception e) {

			return null;
		}
	}


	/**
	 * @Author hejialun
	 * @Date 11:57 2022/11/28
	 * @Description TODO(MultipartFile-转file)
	 * @param file
	 * @return java.io.File
	 */
	public static File multipartFileToFile(MultipartFile file){
		if (file.getSize() <= 0) {
			return null;
		}
		File toFile = null;
		// 用户主目录
		String userHome = System.getProperties().getProperty("user.home");
		StringBuilder filepath = new StringBuilder();
		filepath.append(userHome).append(File.separator).append("files").append(File.separator).append(file.getOriginalFilename()).append(File.separator);

		try {
			//创建文件夹
			toFile = new File(filepath.toString());
			FileUtils.forceMkdir(toFile);

			//创建文件，此时文件为空
			filepath.append(file.getOriginalFilename());
			toFile = new File(filepath.toString());

			//为文件添加流信息
			file.transferTo(toFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return toFile;
	}


	/**
	 * @Author hejialun
	 * @Date 16:38 2022/4/18
	 * @Description TODO(初始化扩展参数-部门具体参数)
	 * @param node：节点对象
	 * @param tree：树数据
	 * @return void
	 */
	public static void initExtra(Object node, Tree<String> tree){
		//获取clazz
		Class<?> a = node.getClass();
		//获取对象的所有变量
		Field[] fields = a.getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			try {
				tree.putExtra(field.getName(),field.get(node));
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}

}
